using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace MicroFractal.iTunesBrowser.Core.Device
{
    public class FolderDevice : BaseDevice
    {

        #region Constructors

        /// <summary>
        /// 
        /// </summary>
        /// <param name="path">Ruta al directorio donde se encuentra la libreria</param>
        public FolderDevice(string serialId, string name, string path)
            : base(serialId, name)
        {
            DirectorySeparatorChar = Path.DirectorySeparatorChar;

            base.DBRootPath = GetRootPath(path);

            if (!File.Exists(Path.Combine(DBRootPath, GetDBFilePath())))
                throw new DevicesNotFoundException();
        }

        #endregion

        #region Properties

        protected override string ControlFolder
        {
            get { return "iPod_Control"; }
        }

        #endregion

        #region Methods

        private string GetRootPath(string path)
        {
            if (path.LastIndexOf("\\") < path.Length - 1)
                path = path + "\\";
            try
            {
                if (File.Exists(Path.Combine(path, GetDBFilePath())))
                {
                    return path;
                }
                if (Path.GetFileName(path) == Properties.Resources.DBFileName)
                {
                    return DownFolderLevel(Path.GetDirectoryName(path),2);
                }
                if (File.Exists(Path.Combine(Path.Combine(path, Properties.Resources.DBFolderName), Properties.Resources.DBFileName)))
                {
                    int from = path.LastIndexOf(this.DirectorySeparatorChar);
                    return path.Remove(from, path.Length - from);
                }
                if (File.Exists(Path.Combine(path, Properties.Resources.DBFileName)))
                {
                    return  DownFolderLevel(path, 2);
                }
            }
            catch { }

            return path;
        }

        private string DownFolderLevel(string path, int count)
        {
            string result = path;
            try
            {
                for (int i = 0; i < count; i++)
                {
                    int from = result.LastIndexOf(this.DirectorySeparatorChar);
                    result = result.Remove(from, result.Length - from);
                }
            }
            catch { }
            return result;
        }

        public override bool IsConnected
        {
            get
            {
                return Directory.Exists(DBRootPath);
            }
            protected set
            {
            }
        }

        public override System.IO.MemoryStream GetDBFile()
        {
            return GetDBFile(false);
        }

        public override System.IO.MemoryStream GetDBFile(bool refresh)
        {
            if (refresh || _DbStream == null)
            {
                if (_DbStream != null)
                    _DbStream.Dispose();

                _DbStream = null;
                try
                {
                    using (FileStream f = File.OpenRead(DBRootPath + GetDBFilePath()))
                    {
                        byte[] b = new byte[f.Length];
                        f.Read(b, 0, (int)f.Length);
                        _DbStream = new MemoryStream(b);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            return _DbStream;
        }

        protected override void Download(MicroFractal.iTunesBrowser.Business.Song song, string downloadPath)
        {
            string filePath = song.Location;

            try
            {

                filePath = filePath.Replace(':', this.DirectorySeparatorChar);

                File.Copy(DBRootPath + filePath, Path.Combine(downloadPath, GetSongFileName(song)));

            }
            catch (Exception ex)
            {
                //TODO Loguear el error
                throw ex;
            }
        }

        public override bool CanCancelDownload
        {
            get
            {
                return true;
            }
            protected set
            { }
        }

        #endregion

        public override string GetFilePath(MicroFractal.iTunesBrowser.Business.Song song)
        {
            string filePath = song.Location;
            filePath = filePath.Replace(':', this.DirectorySeparatorChar);
            return DBRootPath + filePath;
        }

        public override bool CanDirectlyAccessFiles
        {
            get
            {
                return true;
            }
        }
    }
}
